<?PHP
require_once("database.php");
session_start();

function make_string($length){

  srand();
  
  $string = "";
  
  for($i = 0; $i < $length; $i++){
    $number = (rand() % (126-32)) + 32;
    $char = chr($number);
    $string .= $char;
  }
  
  return $string;
}


if($_POST && isset($_POST['username']) && isset($_POST['password']) && trim($_POST['username']) != ""){

  
  
  //Safe-ify inputs
  $name = sql_escape($_POST['username']); 
  $salt = sql_escape(make_string(8));
  $md5pass = md5($salt . $_POST['password']);
  
  // Check if username already exists
  $exists_username = query_select("
    SELECT 1
    FROM user
    WHERE username = '" . $name . "'
  ");
  
  // Check if username already exists
  if(count($exists_username) > 0){
    header('location: createaccount.php?exists');
    exit;
  }	
	
  //table name
  $table = 'user';
	
  //aray of values: username, password, isadmin, salt
  $values = array('username' => $name, 'password' => $md5pass, 'salt' => $salt, 'isadmin' => 0, 'hash' => md5($name)); 

  //insert values into table
  $id = query_insert($table, $values);

  //set session
  $_SESSION['user']= $id;

  //send user to index page
  
  header('location: index.php'); 
  exit;
}

//Else failed, get us out of here!
header('location: createaccount.php');
exit;

?>
